package com.seveneight.baijiesteward.ui.user.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.adapter.LevelAdapter;
import com.seveneight.baijiesteward.base.BaseFragmentBack;
import com.seveneight.baijiesteward.base.MessageEvent;
import com.seveneight.baijiesteward.bean.RankBean;
import com.seveneight.baijiesteward.bean.UserBean;
import com.seveneight.baijiesteward.http.AppConfig;
import com.seveneight.baijiesteward.ui.main.activity.UpdateCodeActivity;
import com.seveneight.baijiesteward.ui.main.contract.LoginContract;
import com.seveneight.baijiesteward.ui.main.fragment.MainFragment;
import com.seveneight.baijiesteward.ui.main.presenter.LoginPresenter;
import com.seveneight.baijiesteward.ui.user.activity.UpgradeActivity;
import com.seveneight.baijiesteward.ui.user.contract.GetRankListContract;
import com.seveneight.baijiesteward.ui.user.presenter.GetRankListPresenter;
import com.seveneight.baijiesteward.utils.NumberUtil;
import com.seveneight.baijiesteward.utils.PreferencesUtil;
import com.seveneight.baijiesteward.utils.StringFormat;
import com.seveneight.baijiesteward.utils.ToastUtil;
import com.seveneight.baijiesteward.utils.WindowUtil;
import com.seveneight.baijiesteward.views.cover.FancyCoverFlow;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by user1 on 2018/2/12.
 */

public class UpgradeFragment extends BaseFragmentBack implements View.OnClickListener, GetRankListContract.GetRankListView, LoginContract.LoginView {

    LoginContract.LoginPresenter loginPresenter;
    GetRankListContract.GetRankListPresenter getRankListPresenter;
    private ImageView iv_back;
    private TextView tv_title;
    private FancyCoverFlow fcf_level;
    private TextView tv_currentlevel;
    private Button bt_submit;
    private LevelAdapter adapter;
    private List<RankBean> data;
    private TextView tv_rate;
    private TextView tv_brokerage;
    private TextView tv_upGradeBrokerage;
    private TextView tv_level1Rate;
    private TextView tv_level2Rate;
    private TextView tv_level3Rate;
    private TextView tv_level1UpGradeBrokerage;
    private TextView tv_level2UpGradeBrokerage;
    private TextView tv_level3UpGradeBrokerage;
    private TextView tv_bottom1;
    private TextView tv_bottom2;
    private TextView tv_bottom3;
    private TextView upgarde_content;
    public UserBean userBean;

    private int selectPosition;

    @Override
    protected int getContentView() {
        return R.layout.fragment_upgrade;
    }

    public static UpgradeFragment newInstance() {
        Bundle args = new Bundle();
        UpgradeFragment fragment = new UpgradeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        iv_back = findView(R.id.iv_back);
        tv_title = findView(R.id.tv_title);
        tv_title.setText("付费升级");
        fcf_level = findView(R.id.fcf_level);
        tv_currentlevel = findView(R.id.tv_currentlevel);
        bt_submit = findView(R.id.bt_submit);
        tv_rate = findView(R.id.tv_rate);
        tv_brokerage = findView(R.id.tv_brokerage);
        tv_upGradeBrokerage = findView(R.id.tv_upGradeBrokerage);
        tv_level1Rate = findView(R.id.tv_level1Rate);
        tv_level2Rate = findView(R.id.tv_level2Rate);
        tv_level3Rate = findView(R.id.tv_level3Rate);
        tv_level1UpGradeBrokerage = findView(R.id.tv_level1UpGradeBrokerage);
        tv_level2UpGradeBrokerage = findView(R.id.tv_level2UpGradeBrokerage);
        tv_level3UpGradeBrokerage = findView(R.id.tv_level3UpGradeBrokerage);
        tv_bottom1 = findView(R.id.tv_bottom1);
        tv_bottom2 = findView(R.id.tv_bottom2);
        tv_bottom3 = findView(R.id.tv_bottom3);
        upgarde_content = findView(R.id.upgarde_content);

        fcf_level.setUnselectedAlpha(0.5f);
        fcf_level.setUnselectedSaturation(0.0f);
        fcf_level.setUnselectedScale(0.5f);
        fcf_level.setMaxRotation(0);
        fcf_level.setScaleDownGravity(0.7f);
        fcf_level.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
    }

    @Override
    protected void initData() {
        loginPresenter = new LoginPresenter(this);
        getRankListPresenter = new GetRankListPresenter(this);
        getRankListPresenter.getRankList(mContext, jsonFormat.commonParam());

    }

    @Override
    public void CallBus(MessageEvent messageEvent) {
        super.CallBus(messageEvent);
        if (messageEvent.getType()==110){
            tv_currentlevel.setText(userBean.getRankName());
        }
    }

    @Override
    protected void setListener() {
        bt_submit.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        fcf_level.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                initUI(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initUI(int position) {
        RankBean rankBean = data.get(position);
        upgarde_content.setText(rankBean.getDescription());
        tv_rate.setText(NumberUtil.getPercentFormat(rankBean.getRate()));
        tv_brokerage.setText(StringFormat.formatNumber(rankBean.getBrokerage()) + "元");
        tv_upGradeBrokerage.setText(StringFormat.formatNumber(rankBean.getUpGradeBrokerage()) + "元");
        tv_level1Rate.setText(NumberUtil.getPercentFormat(rankBean.getLevel1Rate()));
        tv_level2Rate.setText(NumberUtil.getPercentFormat(rankBean.getLevel2Rate()));
        tv_level3Rate.setText(NumberUtil.getPercentFormat(rankBean.getLevel3Rate()));
        if (position == data.size() - 1) {
            tv_bottom1.setText("无限裂变:");
            tv_bottom2.setText("下线任一猪小白升级奖励:");
            tv_bottom3.setText("下线任一猪小白升级奖励:");
        } else {
            tv_bottom1.setText("直推升级奖励分佣:");
            tv_bottom2.setText("间推升级奖励分佣:");
            tv_bottom3.setText("间间推升级奖励分佣:");
        }
        tv_level1UpGradeBrokerage.setText(StringFormat.formatNumber(rankBean.getLevel1UpGradeBrokerage()) + "元");
        tv_level2UpGradeBrokerage.setText(StringFormat.formatNumber(rankBean.getLevel2UpGradeBrokerage()) + "元");
        tv_level3UpGradeBrokerage.setText(StringFormat.formatNumber(rankBean.getLevel3UpGradeBrokerage()) + "元");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                _mActivity.onBackPressed();
                break;
            case R.id.bt_submit:
                userBean= JSON.parseObject(PreferencesUtil.get(getContext(),PreferencesUtil.userinfo,""),UserBean.class);
                if (userBean.getIsSetTradePassword()){
                    if (tv_currentlevel.getText().toString().equals("免费试用")){
                        hideDialog();
                    }else {
                        Intent intent = new Intent(mContext, UpgradeActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("level", tv_currentlevel.getText().toString());
                        bundle.putSerializable("data", (Serializable) data);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, AppConfig.REQUEST_CODE_0);
                    }
                }else {
                    new MaterialDialog.Builder(getContext())
                            .title("设置提醒")
                            .titleColorRes(R.color.graytext)
                            .content("请先设置交易密码")
                            .contentColorRes(R.color.graytext)
                            .backgroundColorRes(R.color.white)
                            .negativeColorRes(R.color.mainblue)
                            .negativeText(R.string.negative)
                            .positiveColorRes(R.color.mainblue)
                            .positiveText(R.string.positive)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    MessageEvent event=new MessageEvent(120);
                                    EventBus.getDefault().post(event);
//                                    ((UpgradeFragment) getParentFragment()).startBrotherFragment(ManagerAccountFragment.newInstance());
                                }
                            })
                            .build().show();
                }
                break;
        }
    }

    public void hideDialog(){
        String items[] = {"升级码升级", "付费升级"};
        AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                if (i==1){
                    Intent intent = new Intent(mContext, UpgradeActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("level", tv_currentlevel.getText().toString());
                    bundle.putSerializable("data", (Serializable) data);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, AppConfig.REQUEST_CODE_0);
                }else {
                    startActivity(new Intent(getContext(), UpdateCodeActivity.class));
                }
            }
        });
        builder.show();
    }

    @Override
    public void reBackRankData(List<RankBean> data) {
        this.data = data;
        userBean= JSON.parseObject(PreferencesUtil.get(getContext(),PreferencesUtil.userinfo,""),UserBean.class);
        initLevel(userBean);

    }

    private void initLevel(UserBean userBean) {
        for (int i = 0; i < data.size(); i++) {
            RankBean bean = data.get(i);
            if (bean.getId().equals(userBean.getRankId())) {
                tv_currentlevel.setText(bean.getRankName());
                selectPosition = i;
            }
        }
        adapter = new LevelAdapter(mContext, data);
        fcf_level.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        fcf_level.setSelection(selectPosition, false);
    }

    @Override
    public void reBackkUser(UserBean bean) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConfig.REQUEST_CODE_0 && resultCode == RESULT_OK) {
            loginPresenter.getUserInfo("正在更新用户等级...", mContext, jsonFormat.commonParam());
        }
    }

    @Override
    public void backUserInfo(UserBean userBean) {
        setting.setUserInfo(userBean);
        this.userBean=userBean;
        initLevel(userBean);
    }
    /**
     * start other BrotherFragment
     */
    public void startBrotherFragment(SupportFragment targetFragment) {
        start(targetFragment);
    }
}
